<template>
  <slide-view
    v-empty="!canShowDetail"
    :listener-ids="listenerIDs"
    :no-listener-ids="noListenerIDs"
    :no-listener-class="noListenerClass"
    :body-style="{padding: 0, height: '100%'}"
    xs-empty-icon="nopermission"
    :xs-empty-text="$t('crm.leads.0f9f737ed8401546ca82403ba3571dae')"
    @afterEnter="viewAfterEnter"
    @close="hideView">
    <div ref="crmDetailMain" v-loading="loading" class="detail-main no-padding">
      <flexbox
        v-if="canShowDetail && detailData"
        direction="column"
        align="stretch"
        class="d-container">
        <wk-detail-header
          :subtitle="$t('crm.leads.859b38191585ac80e9c24249061e36a8')"
          :class="{'is-shadow': bodyIsScroll}"
          :title="detailData.name"
          :page-list="pageList"
          :dropdowns="handleOperations"
          @command="headerRightClick"
          @pageChange="pageChange">
          <template slot="left">
            <el-tooltip
              :content="detailData.star == 0 ? $t('crm.leads.10307f15ac46a53bbe7569a00ccd7f74') : $t('crm.leads.3de98bbda3a3e0c1a7c54eed47cb9b47')"
              effect="dark"
              placement="top">
              <i
                v-if="detailData.star == 0"
                class="el-icon-star-off focus-icon"
                @click="toggleStar()" />
              <i
                v-else
                class="wk wk-focus-on focus-icon active"
                @click="toggleStar()" />
            </el-tooltip>
          </template>

          <template slot="right">
            <time-piece v-if="showTimer && isCall" />
            <el-button
              v-if="showTransfer"
              class="head-handle-button"
              @click="headerRightClick('transfer')">
              {{ $t('crm.leads.88ed213ef918c3cc1800382137d1b9f3') }}
            </el-button>
            <el-button
              v-if="showGet"
              class="head-handle-button"
              type="primary"
              @click="headerRightClick('get')">领取</el-button>

            <el-button
              v-if="showAlloc"
              class="head-handle-button"
              @click="headerRightClick('alloc')">分配</el-button>
            <el-button
              v-if="showEdit"
              class="head-handle-button"
              type="primary"
              @click="headerRightClick('edit')">
              {{ $t('crm.leads.3afced5130e0a6307e921e0c8f29f15b') }}
            </el-button>
          </template>
        </wk-detail-header>

        <!-- 标签 -->
        <flexbox v-if="tagInfo" wrap="wrap" class="wk-tags-content">
          <tag-view :value="tagInfo.value" :max-length="Infinity" wrap="wrap">
            <wk-tag
              v-model="tagInfo.value"
              :disabled="tagInfo.disabled"
              :placeholder="tagInfo.placeholder"
              :data="tagInfo"
              :options="tagInfo.setting"
              @change="tagChange($event)">
              <el-tooltip
                slot="reference"
                :content="$t('crm.leads.a371133af45047afdffa12e9e8d1b12c')"
                effect="dark"
                placement="top">
                <el-button
                  type="icon"
                  size="small"
                  icon="wk wk-icon-label-solid" />
              </el-tooltip>
            </wk-tag>
          </tag-view>
        </flexbox>

        <!-- 快捷创建 -->
        <wk-quick-create-bar
          v-if="activityHandle.length > 0"
          :list="activityHandle"
          @command="quickCreateClick" />

        <div class="d-container-body" @scroll="bodyScroll">
          <detail-head-base :list="headDetails" />
          <relative-stage-records
            :id="id"
            :is-seas="isSeasDetail"
            :crm-type="crmType"
            :is-stage-flow="true"
            :detail="detailData"
            @handle="detailHeadHandle" />
          <el-tabs v-model="tabCurrentName" class="top-padding" nav-mode="more">
            <el-tab-pane
              v-for="(item, index) in tabNames"
              :key="index"
              :label="item.label"
              :name="item.name"
              lazy>
              <template slot="label">
                <el-badge
                  :value="item.num"
                  :hidden="item.num <= 0"
                  type="primary">
                  {{ item.label }}
                </el-badge>
              </template>
              <!-- 工商信息 -->
              <business-info-view
                v-if="item.name === 'BusinessInfoView'"
                :name="detailData.leadsName"
                style="padding: 0;"
                :props="{ fillBtnShow: false, isFixed: false, style: {padding: 0, marginBottom: '16px'}, closeShow: false }" />
              <component
                :is="item.name"
                v-else
                :id="id"
                :ref="item.name"
                :detail="detailData"
                :type-list="logTyps"
                :pool-id="detailPoolId"
                :is-seas="isSeasDetail"
                :crm-type="crmType"
                :ignore-fields="canUseEnterprise ? ['leadsName'] : []"
                @handle="detailHeadHandle" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </flexbox>
    </div>

    <!-- 新建编辑 -->
    <c-r-m-all-create
      v-if="crmCreateShow"
      :action="createActionInfo"
      :crm-type="createCRMType"
      @save-success="editSaveSuccess"
      @close="crmCreateShow=false" />

    <!-- 转移 -->
    <transfer-handle
      v-if="transferDialogShow"
      :props="transferHandleProps"
      :dialog-visible.sync="transferDialogShow"
      @handle="detailHeadHandle({type: 'transfer'})" />

    <!-- 客户分配 -->
    <alloc-handle
      :crm-type="crmType"
      :pool-id="detailPoolId"
      :selection-list="[detailData]"
      :dialog-visible.sync="allocDialogShow"
      @handle="detailHeadHandle({type: 'alloc'})" />

    <!-- 放入线索池 -->
    <put-pool-handle
      :visible.sync="putPoolShow"
      :selection-list="[detailData]"
      :crm-type="crmType"
      @handle="detailHeadHandle({type: 'put_seas_leads'})" />
  </slide-view>
</template>

<script>
import {
  crmLeadsReadAPI,
  crmLeadsDeleteAPI,
  crmLeadsTransformAPI,
  crmLeadsReceiveAPI,
  crmLeadsPoolDeleteAPI
} from '@/api/crm/leads'

import SlideView from '@/components/SlideView'
import TransferHandle from '@/components/Page/SelectionHandle/TransferHandle' // 转移
import RelativeStageRecords from '../components/RelativeStageRecords' // 阶段记录
import Activity from '../components/Activity'
import ImportInfo from '../components/ImportInfo' // 重要信息
import CRMEditBaseInfo from '../components/CRMEditBaseInfo' // 线索基本信息
import RelativeFiles from '../components/RelativeFiles' // 相关附件
import RelativeHandle from '../components/RelativeHandle' // 相关操作
import BusinessInfoView from '@/components/Premium/BusinessInfo/View'
import PutPoolHandle from '../components/SelectionHandle/PutPoolHandle' // 放入线索池
import AllocHandle from '../components/SelectionHandle/AllocHandle' // 线索池分配操作

import CRMAllCreate from '../components/CRMAllCreate' // 新建页面
import DetailMixin from '../mixins/Detail'

export default {
  // 线索管理 的 线索详情
  name: 'LeadsDetail',
  components: {
    SlideView,
    TransferHandle,
    RelativeStageRecords,
    Activity,
    CRMEditBaseInfo,
    RelativeFiles,
    RelativeHandle,
    ImportInfo,
    CRMAllCreate,
    BusinessInfoView,
    PutPoolHandle,
    AllocHandle
  },
  mixins: [DetailMixin],
  props: {
    // 详情信息id
    id: [String, Number],
    poolId: [String, Number],
    // 监听的dom 进行隐藏详情
    listenerIDs: {
      type: Array,
      default: () => {
        return ['crm-main-container']
      }
    },
    // 不监听
    noListenerIDs: {
      type: Array,
      default: () => {
        return []
      }
    },
    noListenerClass: {
      type: Array,
      default: () => {
        return ['el-table__body']
      }
    },
    /** 呼出信息 */
    modelData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      // 展示加载loading
      loading: false,
      crmType: 'leads',
      // 线索池规则权限
      poolAuth: {},
      headDetails: [],
      tabCurrentName: 'Activity',
      allocDialogShow: false, // 线索池分配操作提示框
      putPoolShow: false // 客户放入线索池
    }
  },
  computed: {
    // 展示领取
    showGet() {
      return this.isSeasDetail && this.getOperationsPermision('get')
    },

    // 展示分配
    showAlloc() {
      return this.isSeasDetail && this.getOperationsPermision('alloc')
    },

    /**
     * 活动操作
     */
    activityHandle() {
      const temps = []

      // if (this.canCreateFollowRecord) {
      //   temps = [{
      //     type: 'log',
      //     label: '写跟进'
      //   }]
      // }

      return temps
    },

    /**
     * 根据记录筛选
     */
    logTyps() {
      let logTypslist = []
      logTypslist = [
        {
          icon: 'all',
          color: '#2362FB',
          command: '',
          label: this.$t('crm.leads.a4d71a65a49e62ee12b8dfd51ebd719c')
        }
      ]
      if (this.$store.state.crm.isCall) {
        logTypslist.push({
          icon: 'phone',
          color: '#9376FF',
          command: 13,
          label: this.$t('crm.leads.c9699386ea314c8ef2ab804f2d152589')
        })
      }
      return logTypslist
    },

    // 可操作选项
    handleOperations() {
      return this.getOperations(['transform', 'delete'])
    },

    /**
     * tabs
     */
    tabNames() {
      const tempsTabs = [
        { label: this.$t('crm.leads.c58745b34e0f26ea1a7a5b63f607adec'), name: 'Activity' },
        { label: this.$t('crm.leads.002a4d585721cfcf16fccd7af5ea37ce'), name: 'CRMEditBaseInfo' },
        { label: this.$t('crm.leads.7b667475816fe296e8d46fc5f416a937'), name: 'BusinessInfoView' },
        { label: this.$t('crm.leads.b14d8c0b5d7b9d63c57e1e0bd568bdfd'), name: 'RelativeFiles', num: this.tabsNumber.fileCount }
      ]
      if (!this.isWxUser) {
        tempsTabs.push({ label: this.$t('crm.leads.899d53f67d1b9fe67dc61495bc1fc4fe'), name: 'RelativeHandle' })
      }
      return tempsTabs
    }
  },
  mounted() {},
  methods: {
    /**
     * 详情
     */
    getDetial() {
      this.loading = true
      const params = {
        leadsId: this.id
      }

      if (this.poolId) {
        params.poolId = this.poolId
      }
      crmLeadsReadAPI(params)
        .then(res => {
          const resData = res.data || {}
          this.detailData = resData
          // 线索池权限
          this.poolAuth = resData.poolAuthList || {}

          this.headDetails = [
            { title: this.$t('crm.leads.3485384ff0407765ba2c43b30be583a4'), value: resData.source },
            { title: this.$t('crm.leads.feae554e16dcc4e883505c64e85b516b'), value: resData.mobile },
            { title: this.isSeasDetail ? '前负责人' : this.$t('crm.leads.60588327da6153abe21ec0f9d651fcf6'), value: this.isSeasDetail ? resData.preOwnerUserName : resData.ownerUserName, formType: 'user' },
            { title: this.$t('crm.leads.5cdfeb9d47b470b0a6c90cfadc6faf62'), value: resData.createTime }
          ]
          this.loading = false
        })
        .catch(() => {
          this.loading = false
          this.hideView()
        })
    },

    /**
     * 关闭
     */
    hideView() {
      this.$emit('hide-view')
    },

    /* ------------------------ 头部事件 ------------------------ */
    /**
     * @description: 头部右侧点击事件
     * @param {*}
     * @return {*}
     */
    headerRightClick(type) {
      if (type === 'transfer') {
        this.transferDialogShow = true
      } else if (type === 'edit') {
        this.createCRMType = this.crmType
        this.createActionInfo = {
          type: 'update',
          id: this.id,
          batchId: this.detailData.batchId
        }
        this.crmCreateShow = true
      } else if (type == 'delete') {
        this.$confirm(
          this.$t('crm.leads.b07eaf92d6ad1fa8c08fcab0e92e50ea'),
          this.$t('crm.leads.b02fd239454da490a6fcc384c4796bb4'),
          {
            confirmButtonText: this.$t('crm.leads.1e04e88f51c3817100fe811a7138eed4'),
            cancelButtonText: this.$t('crm.leads.17b48b22c2fafd04e6b4a744e18ee442'),
            type: 'warning'
          }
        )
          .then(() => {
            if (this.isSeasDetail) {
              crmLeadsPoolDeleteAPI({
                poolId: this.detailPoolId,
                ids: [this.id]
              })
                .then(res => {
                  this.$message({
                    type: 'success',
                    message: this.$t('crm.leads.3ab461ef3dbceb50da041862b1706dc2')
                  })
                  this.detailHeadHandle({ type })
                })
                .catch(() => {})
            } else {
              crmLeadsDeleteAPI([this.id])
                .then(res => {
                  this.$message({
                    type: 'success',
                    message: this.$t('crm.leads.3ab461ef3dbceb50da041862b1706dc2')
                  })
                  this.detailHeadHandle({ type })
                })
                .catch(() => {})
            }
          })
          .catch(() => {})
      } else if (type == 'transform') {
        this.$confirm(
          this.$t('crm.leads.727a675b4b3e60abccf0d416b8ea16b4'),
          this.$t('crm.leads.63cc44d4296b3677bcd90ca737f33d16'),
          {
            confirmButtonText: this.$t('crm.leads.63cd8bfbda80e00156cd006197d8a832'),
            cancelButtonText: this.$t('crm.leads.e25a5396d66204c9dd4b9f5be45a788d'),
            type: 'warning'
          }
        )
          .then(() => {
            crmLeadsTransformAPI([this.id])
              .then(res => {
                this.$message({
                  type: 'success',
                  message: this.$t('crm.leads.b3edde66777e1aa09e870b6738187ad2')
                })
                // 刷新待办
                this.$store.dispatch('GetMessageNum')

                this.detailHeadHandle({ type })
              })
              .catch(() => {})
          })
          .catch(() => {})
      } else if (type == 'alloc') {
        // 线索池分配操作
        this.allocDialogShow = true
      } else if (type === 'get') {
        // 领取
        crmLeadsReceiveAPI({
          ids: [this.id],
          poolId: this.detailPoolId
        })
          .then(res => {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
            // 刷新待办
            this.$store.dispatch('GetMessageNum')

            this.detailHeadHandle({ type })
          })
          .catch(() => {})
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/crmdetail.scss";

.d-container-body {
  margin-top: 8px;
}

.import-info {
  height: 100%;
  overflow: auto;
}
</style>
